package jsu.yym.tiktok.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;;
import com.google.gson.Gson;
import jsu.yym.tiktok.mapper.FansMapper;
import jsu.yym.tiktok.mapper.VideoMapper;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.pojo.Video;
import jsu.yym.tiktok.mapper.Type;
import jsu.yym.tiktok.mapper.UserMapper;
import jsu.yym.tiktok.server.*;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
import com.google.gson.JsonObject;


import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;


@Service
public class VideoService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Resource
    private CollaborativeFiltering collaborativeFiltering;
    @Resource
    private QiniuMediaUtilService qiniuMediaUtilService;
    @Autowired
    private FansMapper fansMapper;
    ObjectMapper objectMapper = new ObjectMapper();


    //获取推荐视频
    public ResponseResult getVideo(){
        List<Video> videos = videoMapper.getVideoByState(1);
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
//        System.out.println(id);
            videos = intelligentRecommendation(videos,id);


        if (Objects.isNull(videos)) {
            List<Video> videosList = videoMapper.getVideoByState(1);
            videosList=new VideoComparator().sortVideos(videosList);
            return new ResponseResult(200,"获取成功",videosList);
        }

        return new ResponseResult(200,"获取成功",videos);
    }


    //智能推荐算法
    public List<Video> intelligentRecommendation(List<Video> videos,String id)
    {
        User user = userMapper.getUserByUserName(id);
        //获取推荐的list集合
        List<Video> videoList = collaborativeFiltering.recommendVideos(user);

        //获取用户的标签
        String targe = userMapper.getTargeByUserName(id);
        //根据用户的targe和相关分类视频的浏览量进行排序
        if (Objects.isNull(videoList)) {
            return null;
        }
        Collections.sort(videos, new VideoComparator(targe));

        for (Video c:videos) {
            if(!videoList.contains(c))
                videoList.add(c);
        }

        return videoList;
    }

    //视频上传
    public Video uploadVideo( MultipartFile file)
    {
        //上传视频
        Video user = qiniuMediaUtilService.uploadVideoFile(file);
        //视频转码并且加水印
        qiniuMediaUtilService.qiNiuTransCodeWithWatermark(user.getFileName());
        try {
            //视频审核
            String s = qiniuMediaUtilService.VideoCensor(user.getSrc());
//            String s1 = resourcesCensor.ImageCensor();
//            System.out.println(resourcesCensor.getVideoCensorResultByJobID(s));
            // 创建Gson对象
            Gson gson = new Gson();
            // 解析JSON字符串
            JsonObject jsonObject = gson.fromJson(s, JsonObject.class);
            // 获取字段的值
            String jobValue = jsonObject.get("job").getAsString();
            System.out.println(jobValue);
            String re = qiniuMediaUtilService.getVideoCensorResultByJobID(jobValue);
            System.out.println(re);
            if(re.equals(Type.BLOCK))
            {
                //删除视频
                if (qiniuMediaUtilService.delete(user.getFileName())) {
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("通过审核");
        System.out.println(user.getSrc());
        //生成视频封面
        String image = qiniuMediaUtilService.qiNiuMediaPrtScreen(user.getFileName());
        user.setImage(image);
        return user;
    }

    //检查图片
    public String check(String type) throws Exception
    {
//        System.out.println(result);
        switch (type){
            case "block": return Type.BLOCK;
            case "review":return Type.REVIEW;
            case "pass":return Type.PASS;
        }
        return null;
    }


    //同城推荐，根据地址获取对应的视频
    public ResponseResult getVideoByAddress()
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        String address = userMapper.getAddressByUserName(id);
        //获取相同地址的user
        List<User> list = userMapper.getUserByAddressAndState(address,1);
        System.out.println(address);
        if (address.equals("无")) {
            return new ResponseResult(409,"还没设置地址");
        }
        //获取所有公开视频
        List<Video> videos = videoMapper.getVideoByState(1);
        //寻找同城视频
        List<Video> addressList = new ArrayList<>();
        for (User u:list) {
            for (Video v:videos) {
                if(u.getUsername().equals(v.getUsername()))
                    addressList.add(v);
            }
        }

        if (Objects.isNull(addressList)) {
            return new ResponseResult(503,"获取失败");
        }
        return new ResponseResult(200,"获取成功",addressList);
    }

    //根据标签获取对应的视频
    public ResponseResult getVideoByLabel(String label)
    {
        //获取所有的video
        List<Video> videos = videoMapper.getVideoByState(1);
        List<Video> videoList = new ArrayList<>();
        //获取包含对应标签的list集合
        for (Video v:videos) {
            if(v.getLabel().contains(label))
                videoList.add(v);
        }
        // 使用 Collections.sort 方法和自定义比较器根据浏览量进行排序
        Collections.sort(videoList, new Comparator<Video>() {
            @Override
            public int compare(Video video1, Video video2) {
                // 根据 count 属性从大到小进行排序
                return Integer.compare(video2.getCount(), video1.getCount());
            }
        });
        if (Objects.isNull(videoList)) {
            return new ResponseResult(503,"该视频分类还没有视频呢");
        }
        return new ResponseResult(200,"获取成功",videoList);
    }

    //获取用户关注的人的所有的videoList
    public ResponseResult getFocusVideo()
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        List<String> list = fansMapper.getPersonIdsByUsername(id);
        if(list.isEmpty())
            return new ResponseResult(409,"还没有关注的人");
        List<Video> videos = videoMapper.getVideoByState(1);
        List<Video> focus = new ArrayList<>();
        for (String a:list) {
            for (Video v:videos) {
                if(v.getUsername().equals(a))
                    focus.add(v);
            }
        }
        if(focus.isEmpty())
        {
            return new ResponseResult(409,"还没有关注的人");
        }
        return new ResponseResult(200,"成功",focus);
    }

    //添加视频到es中
    public void saveVideoToElasticsearch(Video video) {
        RestHighLevelClient elasticsearchClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        try {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest("video"); // 索引名称
            indexRequest.id(String.valueOf(video.getPkId())); // 使用 Video 对象的 pkId 作为文档 ID
            String json = videoToJson(video); // 将 Video 对象转为 JSON 字符串
            indexRequest.source(json, XContentType.JSON);

            // 执行索引请求
            elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

    public void updateVideoInElasticsearch(Video video) {
        RestHighLevelClient elasticsearchClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        try {
            // 创建更新请求
            UpdateRequest updateRequest = new UpdateRequest("video", String.valueOf(video.getPkId()));
            String videoJson = videoToJson(video);

            // 设置更新内容
            updateRequest.doc(videoJson, XContentType.JSON);

            // 执行更新请求
            elasticsearchClient.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        } finally {
            try {
                elasticsearchClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String videoToJson(Video video) {
        // 这里你可以使用 JSON 序列化库将 Video 对象转为 JSON 字符串
        // 你可以使用 Jackson、Gson 等库来进行转换
        // 以下示例使用 Jackson：
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String s = objectMapper.writeValueAsString(video);
            System.out.println(s);
            return s;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public void test(){
        List<Video> videos = videoMapper.selectList(null);
        for (Video v:videos) {
            saveVideoToElasticsearch(v);
        }
    }


//    //检查文本
//    public String checkText(String text) throws Exception
//    {
//        String id=qiNiuExamine.TextCensor(text);
//        JsonNode jsonNode = objectMapper.readTree(id);
//        // 提取"suggestion"的值
//        String suggestionValue = jsonNode.path("result").path("suggestion").asText();
//        System.out.println(suggestionValue);
////        System.out.println(result);
//        switch (suggestionValue){
//            case "block": return Type.BLOCK;
//            case "review":return Type.REVIEW;
//            case "pass":return Type.PASS;
//        }
//        return null;
//    }
//
//    //检查视频
//    public String checkVideo(String url) throws Exception
//    {
//        String id = qiNiuExamine.VideoCensor(url);
//        String result = qiNiuExamine.getVideoCensorResultByJobID(id);
//        JsonNode jsonNode = objectMapper.readTree(id);
//        // 提取"suggestion"的值
//        String suggestionValue = jsonNode.path("result").path("suggestion").asText();
//        System.out.println(suggestionValue);
////        System.out.println(result);
//        switch (suggestionValue){
//            case "block": return Type.BLOCK;
//            case "review":return Type.REVIEW;
//            case "pass":return Type.PASS;
//        }
//        return null;
//    }


}
